import Vue from 'vue'
import Vuex from 'vuex'
import Cookies from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: Cookies.get('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}'),
    permissions: JSON.parse(localStorage.getItem('userPermissions') || '[]'),
    // 流程设计器相关状态
    nodeMap: new Map(),
    isEdit: null,
    selectedNode: {},
    design: {
      formItems: [],
      process: {
        // 节点ID，当前流程内唯一，由前端随机生成
        id: "root",
        parentId: null, // 父级节点ID，用来向上搜索
        // 节点类型，ROOT(发起人，根节点)、APPROVAL(审批)、CC(抄送)、CONDITION(条件)、CONCURRENT（并行节点）、DELAY(延时节点)、EMPTY(空节点，占位)
        type: "ROOT",
        name: "发起人",
        props: {
          assignedUser: []
        }, // 节点属性，见下方props说明
        children: {}, // 子节点项，内部字段与当前结构相同，为条件/并行 节点的组合末端节点
      }
    }
  },
  
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      Cookies.set('token', token)
    },
    
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    
    SET_PERMISSIONS(state, permissions) {
      state.permissions = permissions
      localStorage.setItem('userPermissions', JSON.stringify(permissions))
    },
    
    LOGOUT(state) {
      state.token = ''
      state.user = {}
      state.permissions = []
      Cookies.remove('token')
      localStorage.removeItem('user')
      localStorage.removeItem('userPermissions')
    },
    
    // 流程设计器相关mutations
    selectedNode(state, val) {
      state.selectedNode = val
    },
    
    loadForm(state, val) {
      state.design = val
    },
    
    setIsEdit(state, val) {
      state.isEdit = val
    },
    
    // 更新流程状态
    updateProcess(state, process) {
      state.design.process = process
    }
  },
  
  actions: {
    setToken({ commit }, token) {
      commit('SET_TOKEN', token)
    },
    
    setUser({ commit }, user) {
      commit('SET_USER', user)
    },
    
    setPermissions({ commit }, permissions) {
      commit('SET_PERMISSIONS', permissions)
    },
    
    logout({ commit }) {
      commit('LOGOUT')
    }
  },
  
  getters: {
    token: state => state.token,
    user: state => state.user,
    permissions: state => state.permissions,
    isLoggedIn: state => !!state.token
  }
})

